//
//  FilePreview.m
//  file_open
//
//  Created by gl.inet on 2021/12/9.
//

#import "FilePreview.h"

@interface CustomURLSchemeHandler : NSObject <WKURLSchemeHandler>

@end

@implementation CustomURLSchemeHandler

//这里拦截到URLScheme为customScheme的请求后，根据自己的需求,返回结果，并返回给WKWebView显示
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask{
    NSURL *url = [NSURL URLWithString: [urlSchemeTask.request.URL.absoluteString stringByReplacingOccurrencesOfString:@"filehttp" withString:@"http"]];
    NSURLRequest *request = [NSURLRequest  requestWithURL:url];
    NSLog(@"request = %@",request);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSURLResponse *response2 = [[NSURLResponse alloc] initWithURL:urlSchemeTask.request.URL MIMEType:@"application/pdf" expectedContentLength:data.length textEncodingName:nil];
        [urlSchemeTask didReceiveResponse:response2];
        [urlSchemeTask didReceiveData:data];
        [urlSchemeTask didFinish];
    }];
    [task resume];

}

- (void)webView:(WKWebView *)webVie stopURLSchemeTask:(id)urlSchemeTask {
}
@end

@implementation FilePreview
- (instancetype)initWithFrame:(CGRect)frame
               viewIdentifier:(int64_t)viewId
                    arguments:(id _Nullable)args
              binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
  if (self = [super init]) {


    WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
    CustomURLSchemeHandler *handler = [CustomURLSchemeHandler new];
    [configuration setURLSchemeHandler:handler forURLScheme:@"filehttp"];
    self.webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration];

    self.channel = [FlutterMethodChannel methodChannelWithName:[NSString stringWithFormat:@"xyx/file_preview_%d",viewId] binaryMessenger:messenger];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    __weak typeof(self) weakSelf = self;
    [_channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
     
        
        if([call.method isEqual: @"load_file"]){
            NSString *path = call.arguments[@"path"];
            [weakSelf.webView loadFileURL:[NSURL fileURLWithPath:path] allowingReadAccessToURL:[NSURL fileURLWithPath:path]];
            result(@(true));
        }if([call.method isEqual: @"load_url"]){
            NSString *url = call.arguments[@"url"];
            ///pdf单独处理 服务器返回的类型有问题
           
            if([url hasSuffix:@".pdf"]){
              [weakSelf.webView loadRequest:[NSURLRequest  requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"file%@",url]]]];
            }else{
              [weakSelf.webView loadRequest:[NSURLRequest  requestWithURL:[NSURL URLWithString:url]]];
            }
            result(@(true));
        }else{
            result(FlutterMethodNotImplemented);
        }
    }];

  }
  return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    //加载进度值
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (object == self.webView)
        {
          // NSLog(@"%f", self.webView.estimatedProgress);
          [_channel invokeMethod:@"file_load_progress" arguments:[NSNumber numberWithDouble:self.webView.estimatedProgress]];
            // if(self.webView.estimatedProgress == 1.0){
                
            // }

        }

    }

}

- (void)dealloc{
  [self.webView stopLoading];
  [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (UIView*)view {
  return self.webView;
}

@end




